﻿using BigMonitoringWarningApi.Model.ApiResult;
using BigMonitoringWarningApi.Tool.Extension;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.API;
using GYCTOAManagementSystemNewApi.Model.DTO.KnowledgeFile;
using GYCTOAManagementSystemNewApi.Model.Entity;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Model.ViewModel;
using GYCTOAManagementSystemNewApi.Public;
using GYCTOAManagementSystemNewApi.Service;
using GYCTOAManagementSystemNewApi.Tool;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    /// <summary>
    /// 证书管理
    /// </summary>
    public class CertificateManagementController : BaseController
    {
        private readonly ILogger<CertificateManagementController> _logger;
        DBContext _db;

        public CertificateManagementController(ILogger<CertificateManagementController> logger, DBContext db)
        {
            _logger = logger;
            _db = db;
        }

        /// <summary>
        /// 数据查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Test()
        {
            return ApiResult.True();
        }


        #region 证书管理
        /// <summary>
        /// 数据查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiPageResult> GetCertificateManagementDetail([FromBody] dynamic formData)
        {
            try
            {
                JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
                int offset = Convert.ToInt32(j_token["currentPage"]);
                int limit = Convert.ToInt32(j_token["pagesize"]);
                var Key = j_token["key"].ToString();
                var query = _db.CertificateManagement.Where(x => !x.Delete);
                if (!string.IsNullOrWhiteSpace(Key))
                {
                    query = query.Where(x => x.CertificateName.Contains(Key)
                    );
                }
                var total = query.Count();
                var rows = await query.Skip((offset - 1) * limit).Take(limit).ToListAsync();
                return ApiPageResult.True(rows, offset, limit, total);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="arrDel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteCertificateManagementContent(int[] arrDel)
        {
            var UserId = HttpContext.User.Claims.FirstOrDefault().Value;
            {
                using (System.Transactions.TransactionScope ts = new TransactionScope())
                {
                    foreach (var t in arrDel)
                    {
                        var obj = _db.CertificateManagement.Find(t);
                        if (obj == null)
                        {
                            return ApiResult.False();
                        }
                        obj.Delete = true;
                        obj.OperatDate = DateTime.Now;
                        obj.OperatId = Convert.ToInt32(UserId);
                    }
                    ts.Complete();
                }
            }
            if (await _db.SaveChangesAsync() > 0)
            {
                return ApiResult.True();
            }
            return ApiResult.False("信息提交失败");
        } 
        /// <summary>
        /// 添加文档
        /// </summary>
        /// <param name="CertificateManagement"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> AddCertificateManagementContent( [FromBody] dynamic formData)
        {
            CertificateManagement certificateManagement = JsonConvert.DeserializeObject<CertificateManagement>(formData.ToString());
            /*(CertificateManagement CertificateManagement){*/
        var UserId = HttpContext.User.Claims.FirstOrDefault().Value;
            certificateManagement.OperatDate = DateTime.Now;
            certificateManagement.OperatId = UserId.ToInt();
            //if (_db.CertificateManagement.Where(x => x.CertificateName.Equals(certificateManagement.CertificateName) && !x.Delete).Count() > 0)
            //{
            //    return ApiResult.False("已存在相同的名称请删除后再次添加");
            //}
            _db.CertificateManagement.Add(certificateManagement);
            if (await _db.SaveChangesAsync() > 0)
            {
                return ApiResult.True();
            }
            return ApiResult.False("信息提交失败");
        }
        /// <summary>
        /// 修改文档
        /// </summary>
        /// <param name="CertificateManagement"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateCertificateManagementContent([FromBody] dynamic formData)
        {
            CertificateManagement certificateManagement = JsonConvert.DeserializeObject<CertificateManagement>(formData.ToString());
            try
            {
                var UserId = HttpContext.User.Claims.FirstOrDefault().Value;
                certificateManagement.OperatDate = DateTime.Now;
                certificateManagement.OperatId = UserId.ToInt();
                _db.CertificateManagement.Update(certificateManagement);
                if (await _db.SaveChangesAsync() > 0)
                {
                    return ApiResult.True();
                }
                return ApiResult.False("信息提交失败");
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
            }
        }
        #endregion
    }
}